package com.caiheng.api.controller.estate;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.entity.attendance.*;
import com.caiheng.api.entity.examine.ExamineApproveRegImg;
import com.caiheng.api.entity.examine.ExamineApproveRegRecord;
import com.caiheng.api.service.attendance.*;
import com.caiheng.api.util.*;
import com.vdurmont.emoji.EmojiParser;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.estate.Estate;
import com.caiheng.api.entity.sys.SysDictData;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.estate.EstateService;
import com.caiheng.api.service.estate.EstateUserService;
import com.caiheng.api.service.estate.PropertyUserService;
import com.caiheng.api.service.sys.SysDictDataService;
import com.caiheng.api.service.sys.SysUserService;
import com.caiheng.api.service.wxuser.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  考勤相关
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/attendance")//url:模块/资源/{}/细分
public class AttendanceController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private AttendanceService attendanceService;
    @Resource
    private AttendanceImgService attendanceImgService;
    @Resource
    private AttendanceOffWorkService attendanceOffWorkService;
    @Resource
    private AttendanceGroupService attendanceGroupService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private AttendanceGroupUserService attendanceGroupUserService;
    @Resource
    private EstateService estateService;
    @Resource
    private SysDictDataService sysDictDataService;
    @Resource
    private EstateUserService estateUserService;
    @Resource
    private PropertyUserService propertyUserService;

    @Value("${web.imgPrefixOss}")
    private String imgPrefix;//图片地址

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址



    /**
     *  根据手机号查询当前手机号所导入的后台管理员账号（仅限于物业人员和 小区工作人员）
     * @param
     * @throws Exception
     */
    @PostMapping(value="/group/user/list")
    public JSONObject userList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "attendance/group/user/list 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            if(StrUtil.isEmpty(phone_num)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"手机号不能为空"),true,true);
            }

            Map<String,Object> map = new HashMap<>();

            Map<String,Object> mapEstate = new HashMap<>();
            mapEstate.put("phone_num",phone_num);
            List<AttendanceGroupUser> attendanceGroupUsers = attendanceGroupUserService.selectAttendanceGroupUserList(mapEstate);
            for (AttendanceGroupUser groupUser : attendanceGroupUsers){
                AttendanceGroup group = attendanceGroupService.findById(groupUser.getGroupId());
                if(group!=null){
                    groupUser.setGroupName(group.getGroupName());
                }
                SysUser sysUser = sysUserService.findById(groupUser.getSysUserId());
                if(sysUser != null){
                    groupUser.setSysUserName(sysUser.getNickName());
                }
                if(groupUser.getUserId().intValue() == user_id){
                    groupUser.setIsBand(1);
                }
            }
            map.put("attendanceUsers",attendanceGroupUsers);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功", map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  根据手机号查询当前手机号所导入的后台管理员账号（仅限于物业人员和 小区工作人员）
     * @param
     * @throws Exception
     */
    @PostMapping(value="/band/group/user")
    public JSONObject bandUser(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "attendance/band/group/user 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int user_type = jsonRequest.containsKey("user_type") ? jsonRequest.getInt("user_type") : 0;
            long sys_user_id = jsonRequest.containsKey("sys_user_id") ? jsonRequest.getLong("sys_user_id") : 0;
            int group_user_id = jsonRequest.containsKey("group_user_id") ? jsonRequest.getInt("group_user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(sys_user_id);
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该人员账号不存在"),true,true);
            }

            if(sysUser.getStatus().equals("1")){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该账号已禁用"),true,true);
            }

            AttendanceGroupUser groupUser = attendanceGroupUserService.findById(group_user_id);
            if(groupUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该考勤账号不存在"),true,true);
            }

            if(groupUser.getUserId() !=null && groupUser.getUserId() > 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该账号已被其他用户绑定"),true,true);
            }
            groupUser.setUserId(user_id);
            boolean bl = attendanceGroupUserService.updateById(groupUser);
            if(bl){
                user.setDutySysUserId(sys_user_id);
                bl = userService.updateById(user);
                if(bl){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"绑定成功"),true,true);
                }else {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "绑定失败"), true, true);
                }
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"绑定失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  根据手机号查询当前手机号所导入的后台管理员账号（仅限于物业人员和 小区工作人员）
     * @param
     * @throws Exception
     */
    @PostMapping(value="/unBand/group/user")
    public JSONObject unBandUser(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "attendance/unBand/group/user 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int user_type = jsonRequest.containsKey("user_type") ? jsonRequest.getInt("user_type") : 0;
            int sys_user_id = jsonRequest.containsKey("sys_user_id") ? jsonRequest.getInt("sys_user_id") : 0;
            int group_user_id = jsonRequest.containsKey("group_user_id") ? jsonRequest.getInt("group_user_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(sys_user_id);
            if(sysUser == null) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该人员账号不存在"),true,true);
            }

            if(sysUser.getStatus().equals("1")) {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该账号已禁用"),true,true);
            }

            AttendanceGroupUser groupUser = attendanceGroupUserService.findById(group_user_id);
            if(groupUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该绑定信息不存在"),true,true);
            }
            if(groupUser.getUserId() != null && groupUser.getUserId().intValue() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定该用户"),true,true);
            }
            groupUser.setUserId(0);
            boolean bl = attendanceGroupUserService.updateById(groupUser);
            if(bl){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"解绑成功"),true,true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"解绑失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 考勤打卡界面请求数据
     * @param requestParam
     * @return
     */
    @PostMapping(value = "/view")
    public JSONObject attendanceDetail(@RequestBody String requestParam) {
        JSONObject result = null;
        try {
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logger.info("考勤详情 attendance/view 接收参数：" + requestParam.toString());
            System.out.println("attendance/view 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            double lng = jsonRequest.containsKey("lng") ? jsonRequest.getDouble("lng") : 0d;
            double lat = jsonRequest.containsKey("lat") ? jsonRequest.getDouble("lat") : 0d;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            Map<String,Object> map = new HashMap<>();

            map.put("is_in_range", 0);
            map.put("is_band_sys_user",0);
            map.put("is_check_holiday",0);
            map.put("holiday_check_count",0);

            Map<String,Object> mapLeaveTime = new HashMap<>();
            mapLeaveTime.put("userId",user_id);
            mapLeaveTime.put("beginTime",DateUtil.getMonthFirstDay());
            mapLeaveTime.put("endTime",DateUtil.getMonthLastDay());
            Double leaveTimeThisMonth = attendanceService.getLeaveDaysByUserId(mapLeaveTime);
            map.put("leaveTime",leaveTimeThisMonth);

            if(StrUtil.isNotEmpty(user.getFaceUrl())){
                if(user.getFaceUrl().contains("https")){
                    map.put("faceUrl",user.getFaceUrl());
                }else{
                    map.put("faceUrl", imgPrefix + user.getFaceUrl());
                }
            }

            List<String> groupNames = new ArrayList<>();
            Map<String,Object> mapGroup = new HashMap<>();
            mapGroup.put("sysUserId", user.getSysUserId());
            List<AttendanceGroup> myGroupList = attendanceGroupService.selectAttendanceGroupList(mapGroup);

            AttendanceGroupUser groupUserHoliday = attendanceGroupUserService.getCheckHolidayManager(0, user);
            if(groupUserHoliday != null) {
                map.put("is_check_holiday", groupUserHoliday.getIsCheckHoliday());
                //获取请假的个数
                QueryWrapper<Attendance> qw = new QueryWrapper<>();
                qw.select("id");
                qw.eq("property_id", groupUserHoliday.getPropertyId());
                qw.eq("state",4);
                qw.eq("holiday_state",1);
                long checkCount = attendanceService.count(qw);
                map.put("holiday_check_count",checkCount);
            }


//            Integer[] userTypes = { 2, 3};
//            QueryWrapper<SysUser> qw = new QueryWrapper<>();
//            qw.eq("user_id",user.getSysUserId());
//            qw.in("user_type", Arrays.asList(userTypes));
//            qw.last("limit 1");
            AttendanceGroupUser groupUser = attendanceGroupUserService.getDefaultGroup(user);
            if(groupUser != null){
                map.put("is_band_sys_user",1);
                SysUser sysUser = sysUserService.findById(groupUser.getSysUserId());
                map.put("sys_user_name", sysUser.getNickName());

                AttendanceGroup attendanceGroup = attendanceGroupService.selectAttendanceGroupByUserId(groupUser);
                if (attendanceGroup != null) {

                    if(myGroupList.isEmpty()){
                        myGroupList.add(attendanceGroup);
                    }
                    map.put("defaultGroup", attendanceGroup);
                    map.put("duty_group_name", attendanceGroup.getGroupName());
                    map.put("property_name", attendanceGroup.getPropertyName());
                    map.put("estate_name", attendanceGroup.getEstateName());

                    double distance = GetDistance.distance(attendanceGroup.getLng().doubleValue(),attendanceGroup.getLat().doubleValue(), lng,lat);
//                    System.out.println("距离： " + distance + "米");
                    if(distance <= attendanceGroup.getSignRange()){
                        map.put("is_in_range", 1);
                    }


                    Date nowDate = new Date();
                    Date amBeginDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getAmBeginDutyTime() + ":00");
                    Date amEndDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getAmEndDutyTime() + ":00");
                    Date pmBeginDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getPmBeginDutyTime() + ":00");
                    Date pmEndDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getPmEndDutyTime() + ":00");

                    int amEndDutyHour = attendanceGroup.getAmEndDutyHour();
                    Date amEndDutyTimeAfter = DateUtil.getAfterSecondsByOld(amEndDutyTime,amEndDutyHour * 60 * 60);
                    Date pmBeginDutyTimeBefore =  DateUtil.getAfterSecondsByOld(pmBeginDutyTime,-amEndDutyHour * 60 * 60);

                    Date zeroTime = DateUtil.fomatTime(DateUtil.getDay() + " 00:00:00");
                    Date lastTime = DateUtil.fomatTime(DateUtil.getDay() + " 23:59:59");

                    map.put("am_begin_duty_time", attendanceGroup.getAmBeginDutyTime());
                    map.put("am_end_duty_time", attendanceGroup.getAmEndDutyTime());
                    map.put("pm_begin_duty_time", attendanceGroup.getPmBeginDutyTime());
                    map.put("pm_end_duty_time", attendanceGroup.getPmEndDutyTime());


                    map.put("am_begin_duty_time_user", "未打卡");
                    map.put("am_end_duty_time_user", "未打卡");
                    map.put("pm_begin_duty_time_user", "未打卡");
                    map.put("pm_end_duty_time_user", "未打卡");

                    map.put("am_begin_duty_state", 0);
                    map.put("am_end_duty_state", 0);
                    map.put("pm_begin_duty_state", 0);
                    map.put("pm_end_duty_state", 0);
                    map.put("is_late_am", "");
                    map.put("is_late_pm", "");

                    String nowSignTime = "";
                    // 0 -上午上班打卡时间   1 - 上午下班打卡时间  2 - 下午上班打卡时间 3 - 下午下班打卡时间
                    int nowSignType = 0;
                    // 0 -上午上班打卡时间   1 - 上午下班打卡时间  2 - 下午上班打卡时间 3 - 下午下班打卡时间
                    int isLateState = 0;

                    //8点半之前 和 下班之前都可以进行打 上午上班卡
                    //0点 到 上午上班之前的
                    if (zeroTime.getTime() <= nowDate.getTime() && nowDate.getTime() < amEndDutyTimeAfter.getTime()) {//打上班卡
                        nowSignType = 0;//记录当前是哪个阶段
                        nowSignTime = DateUtil.getSimpleTime(amBeginDutyTime);
                        //是否已经打卡过了
                        Attendance attendance = attendanceService.getTodayAttendance(attendanceGroup, user, nowSignType);
                        if(attendance != null){
                            map.put("is_late_am",getIsLate(attendance.getState()));
                            map.put("am_begin_duty_time_user", DateUtil.getSimpleTime(attendance.getCreateTime()));
                            map.put("am_begin_duty_state", 1);
                            nowSignType = 1;//下一步打卡是什么阶段
                        }
                    }

                    //8点半到 上午下班时间
                    if (amBeginDutyTime.getTime() <= nowDate.getTime() && nowDate.getTime() < amEndDutyTimeAfter.getTime()) {//打上班卡
                        nowSignType = 1;//记录当前是哪个阶段
                        nowSignTime = DateUtil.getSimpleTime(amEndDutyTime);
                        Attendance attendance = attendanceService.getTodayAttendance(attendanceGroup,user,nowSignType);
                        if(attendance != null){
//                            map.put("is_late_am",getIsLate(attendance.getState()));
                            map.put("am_begin_duty_time_user", DateUtil.getSimpleTime(attendance.getCreateTime()));
                            map.put("am_begin_duty_state", 1);
                            nowSignType = 2;//下一步打卡是什么阶段
                        }else{
//                            nowSignType = 0;//记录当前是哪个阶段
//                            isLateState = 1;
                            nowSignType = 1;//下一步打卡是什么阶段
                            map.put("am_begin_duty_time_user", "未打卡");
                            map.put("am_begin_duty_state", 0);
                        }
                    }

                    //上午下班时间 到 下午上班时间
                    //中间休息时间可以打 上午的下班时间  和 下午的上班时间
                    if (amEndDutyTime.getTime() <= nowDate.getTime() && nowDate.getTime() < pmBeginDutyTime.getTime()) {//打上班卡

                        nowSignType = 1;//记录当前是哪个阶段
                        nowSignTime = DateUtil.getSimpleTime(amEndDutyTime);

                        //上午下班的打卡记录
                        Attendance attendanceAmEnd = attendanceService.getTodayAttendance(attendanceGroup, user, nowSignType);
                        if(attendanceAmEnd != null){
                            map.put("am_end_state",getIsLate(attendanceAmEnd.getState()));
                            map.put("am_end_duty_time_user", DateUtil.getSimpleTime(attendanceAmEnd.getCreateTime()));
                            map.put("am_end_duty_state", 1);
                            nowSignType = 2;//下一步打卡是什么阶段
                        }else{
                            map.put("am_end_duty_time_user", "未打卡");
                            map.put("am_end_duty_state", 0);
                        }

                        // 下午上班的打卡记录
                        Attendance attendancePmBegin = attendanceService.getTodayAttendance(attendanceGroup, user, 2);
                        if(attendancePmBegin!= null){
                            map.put("is_late_am",getIsLate(attendancePmBegin.getState()));
                            map.put("am_begin_duty_time_user", DateUtil.getSimpleTime(attendancePmBegin.getCreateTime()));
                            map.put("am_begin_duty_state", 1);
                            nowSignType = 3;//下一步打卡是什么阶段
                        }else{
                            map.put("am_begin_duty_time_user", "未打卡");
                            map.put("am_begin_duty_state", 0);
                            nowSignType = 2;//下一步打卡是什么阶段
                        }
                    }


                    //下午上班时间 到 下午下班时间
                    if (pmBeginDutyTimeBefore.getTime() <= nowDate.getTime() && nowDate.getTime() <= pmBeginDutyTime.getTime()) {//打上班卡
                        nowSignType = 2;//记录当前是哪个阶段
                        nowSignTime = DateUtil.getSimpleTime(pmBeginDutyTime);

                        Attendance attendancePmBegin = attendanceService.getTodayAttendance(attendanceGroup,user, nowSignType);
                        if(attendancePmBegin != null){
                            map.put("is_late_pm",getIsLate(attendancePmBegin.getState()));
                            map.put("pm_begin_duty_time_user", DateUtil.getSimpleTime(attendancePmBegin.getCreateTime()));
                            map.put("pm_begin_duty_state", 1);
                            nowSignType = 3;//记录当前是哪个阶段
                        }
                        else{
                            nowSignType = 2;//记录当前是哪个阶段
                        }
                    }


                    // 下午的上班时间范围内
                    if (pmBeginDutyTime.getTime() <= nowDate.getTime() && nowDate.getTime() < pmEndDutyTime.getTime()) {//打上班卡
                        nowSignType = 2;//记录当前是哪个阶段
                        Attendance attendance = attendanceService.getTodayAttendance(attendanceGroup,user, nowSignType);
                        if(attendance != null){
                            map.put("pm_begin_duty_time_user", DateUtil.getSimpleTime(attendance.getCreateTime()));
                            map.put("pm_begin_duty_state", 1);
//                            map.put("is_late_pm",getIsLate(attendance.getState()));
                            nowSignType = 3;//下一步打卡是什么阶段
                        }else{
                            isLateState = 1;
                            map.put("pm_begin_duty_time_user", "未打卡");
                            map.put("pm_begin_duty_state", 0);
                            nowSignType = 2;//下一步打卡是什么阶段
                        }
                    }


                    // 下午下班之间之后的
                    if (pmEndDutyTime.getTime() <= nowDate.getTime() && nowDate.getTime() <= lastTime.getTime()) {//打下班卡
                        nowSignType = 3;
                        nowSignTime = DateUtil.getSimpleTime(pmEndDutyTime);
                        Attendance attendance = attendanceService.getTodayAttendance(attendanceGroup,user,nowSignType);
                        if(attendance != null){
                            map.put("pm_end_duty_time_user", DateUtil.getSimpleTime(attendance.getCreateTime()));
                            map.put("pm_end_duty_state", 1);
//                            map.put("is_late_pm",getIsLate(attendance.getState()));
                        }
                    }



                    //上午上班的打卡记录
                    Attendance attendanceAm = attendanceService.getTodayAttendance(attendanceGroup,user,0);
                    if(attendanceAm != null){
                        map.put("is_late_am", getIsLate(attendanceAm.getState()));
                        map.put("am_begin_duty_time_user", DateUtil.getSimpleTime(attendanceAm.getCreateTime()));
                        map.put("am_begin_duty_state", 1);
                    }else{
                        map.put("am_begin_duty_time_user", "未打卡");
                        map.put("am_begin_duty_state", 0);
                    }

                    //上午下班的打卡记录
                    Attendance attendanceAmEnd = attendanceService.getTodayAttendance(attendanceGroup, user, 1);
                    if(attendanceAmEnd!= null){
//                            map.put("is_late_am",getIsLate(attendanceAmEnd.getState()));
                        map.put("am_end_duty_time_user", DateUtil.getSimpleTime(attendanceAmEnd.getCreateTime()));
                        map.put("am_end_duty_state", 1);
                    }else{
                        map.put("am_end_duty_time_user", "未打卡");
                        map.put("am_end_duty_state", 0);
                    }


                    //下午上班的打卡记录
                    Attendance attendancePmBegin = attendanceService.getTodayAttendance(attendanceGroup,user, 2);
                    if(attendancePmBegin != null){
                        map.put("is_late_pm",getIsLate(attendancePmBegin.getState()));
                        map.put("pm_begin_duty_time_user", DateUtil.getSimpleTime(attendancePmBegin.getCreateTime()));
                        map.put("pm_begin_duty_state", 1);
                    }else{
                        map.put("pm_begin_duty_time_user", "未打卡");
                        map.put("pm_begin_duty_state", 0);
                    }

                    //下午下班的打卡记录
                    Attendance attendancePmEnd = attendanceService.getTodayAttendance(attendanceGroup,user, 3);
                    if(attendancePmEnd != null){
                        map.put("pm_end_duty_time_user", DateUtil.getSimpleTime(attendancePmEnd.getCreateTime()));
                        map.put("pm_end_duty_state", 1);
//                            map.put("is_late_pm",getIsLate(attendance.getState()));
//                        nowSignType = 3; //下一步打卡是什么阶段
//                        nowSignType = 3;//下一步打卡是什么阶段
                    }else{
                        map.put("pm_end_duty_time_user", "未打卡");
                        map.put("pm_end_duty_state", 0);
                    }


                    map.put("isLateState", isLateState);
                    map.put("nowSignType", nowSignType);
                    map.put("nowSignTime", nowSignTime);

                    map.put("is_bang_group",1);
                }else{
                    map.put("is_bang_group",0);
                }
            }

            if(CollUtil.isNotEmpty(myGroupList)) {
                for (AttendanceGroup group : myGroupList) {
                    groupNames.add(group.getGroupName());
                }
            }
            map.put("groupNames", groupNames);
            map.put("myGroupList", myGroupList);


            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功",map),true,false);
        } catch (Exception e) {
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常"),true,true);
            logger.error("考勤详情异常报错", e);
        }
        return result;
    }


    private String getIsLate(Integer state){
        String s = "";
        //1 - 正常  2-  迟到  3- 旷工  4 - 请假
        if(state == 2){
            s = "(迟到)";
        } else if(state == 3){
            s = "(旷工)";
        } else if(state == 4){
            s = "(请假)";
        }
        return s;
    }


    /**
     *  改变当前打卡的默认考勤组
     * @param
     * @throws Exception
     */
    @PostMapping(value="/changeDefaultGroup")
    public JSONObject changeGroup(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "attendance/changeDefaultGroup 接收的参数： " + requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int group_id = jsonRequest.containsKey("group_id") ? jsonRequest.getInt("group_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            AttendanceGroupUser groupUser = attendanceGroupUserService.getGroupBySysUserId(user.getSysUserId(), group_id);
            if(groupUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定该考勤组"),true,true);
            }

            int ret = attendanceGroupUserService.changeDefaultGroup(user, group_id);
            if(ret > 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"更改成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"更改失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 考勤打卡
     * @param requestParam
     * @return
     */
    @PostMapping(value = "/sign")
    public Object attendance(@RequestBody String requestParam) {
        Object result = null;
        try {
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "attendance/sign 接收的参数： " + requestParam);
            System.out.println("attendance/sign 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            logger.info("考勤 attendance/sign 接收参数： " + jsonRequest.toString());
			int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            Double lng = jsonRequest.containsKey("lng") ? jsonRequest.getDouble("lng") : 0;
            Double lat = jsonRequest.containsKey("lat") ? jsonRequest.getDouble("lat") : 0;
            String address = jsonRequest.containsKey("address") ? jsonRequest.getStr("address") : null;
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : null;
            Integer isOut = jsonRequest.containsKey("isOut") ? jsonRequest.getInt("isOut") : null;
            String imgUrl = jsonRequest.containsKey("imgUrl") ? jsonRequest.getStr("imgUrl") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

//            Integer[] userTypes = { 2, 3};
//            QueryWrapper<SysUser> qw = new QueryWrapper<>();
//            qw.eq("user_id",user.getSysUserId());
//            qw.in("user_type", Arrays.asList(userTypes));
//            qw.last("limit 1");
            AttendanceGroupUser groupUser = attendanceGroupUserService.getDefaultGroup(user);
            if(groupUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您未绑定工作人员，无需打卡"),true,true);
            }

            AttendanceGroup attendanceGroup = attendanceGroupService.selectAttendanceGroupByUserId(groupUser);
            if (attendanceGroup != null) {
                LocalDateTime now = LocalDateTime.now();
                //获取当前周
                int weekDay = now.getDayOfWeek().getValue();
//                int isNeedAttend = isNeedDaka(weekDay, attendanceGroup);
//                if (isNeedAttend == 0) {
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"非工作时间，无需打卡"),true,true);
//                }
                if (attendanceGroup.getAmBeginDutyTime() == null || attendanceGroup.getAmEndDutyTime() == null
                    || attendanceGroup.getPmBeginDutyTime() == null || attendanceGroup.getPmEndDutyTime() == null) {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"本考勤组考勤时间配置异常"),true,true);
                }

                Date nowDate = new Date();
                Date amBeginDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getAmBeginDutyTime() + ":00");
                Date amEndDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getAmEndDutyTime() + ":00");
                Date pmBeginDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getPmBeginDutyTime() + ":00");
                Date pmEndDutyTime = DateUtil.fomatTime(DateUtil.getDay() + " " + attendanceGroup.getPmEndDutyTime() + ":00");

                int amEndDutyHour = attendanceGroup.getAmEndDutyHour();
                Date amEndDutyTimeAfter = DateUtil.getAfterSecondsByOld(amEndDutyTime,amEndDutyHour * 60 * 60);
                Date pmBeginDutyTimeBefore =  DateUtil.getAfterSecondsByOld(pmBeginDutyTime,-amEndDutyHour * 60 * 60);

                int pmBeginDutyHour = attendanceGroup.getPmBeginDutyHour();

                Date zeroTime = DateUtil.fomatTime(DateUtil.getDay() + " 00:00:00");
                Date lastTime = DateUtil.fomatTime(DateUtil.getDay() + " 23:59:59");
                Date middleTime = DateUtil.fomatTime(DateUtil.getDay() + " 12:00:00");

                if (attendanceGroup.getIsSpecial() == 1) {
                    isOut = 0;
                }
//                boolean ret = false;
                int ret = 0;
                //8点半之前  和 下班之前都可以进行打 上班卡
                //0 点 ~ 8：30
                if (zeroTime.getTime() <= nowDate.getTime() && nowDate.getTime() < amBeginDutyTime.getTime()) {//打上班卡
                    //进行上班打卡
                    boolean blIsCheck = attendanceService.isCheckAttendance(user, groupUser,0);//判断上午是否打卡
                    if (blIsCheck) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"已打卡，无需打卡"),true,true);
                    }
                    Date halfHourAfter = DateUtil.getDateByMinuts(amBeginDutyTime, 30);
                    Attendance attendance = packageAttendance(user_id, groupUser, lng, lat, address, remark, amBeginDutyTime, isOut, 0, halfHourAfter, imgUrl, attendanceGroup.getId());
                    ret = attendanceService.addCheck(attendance);
                }
                // 上班之后  这段期间 迟到卡  8：30 ~ 11：50
                else if (amBeginDutyTime.getTime() <= nowDate.getTime() && nowDate.getTime() < amEndDutyTime.getTime()) {
                    //进行上班打卡
                    boolean blIsCheck = attendanceService.isCheckAttendance(user, groupUser,0);//判断上午是否打卡
                    if (blIsCheck) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未到下班时间"),true,true);
                    }
                    Date halfHourAfter = DateUtil.getDateByMinuts(amBeginDutyTime, 30);
                    Attendance attendance = packageAttendance(user_id, groupUser, lng, lat, address, remark, amBeginDutyTime, isOut, 0, halfHourAfter, imgUrl, attendanceGroup.getId());
                    ret = attendanceService.addCheck(attendance);
                }
                // 上午的下班卡  11：50 ~  12：50
                else if (amEndDutyTime.getTime() <= nowDate.getTime() && nowDate.getTime() < amEndDutyTimeAfter.getTime()) {//打上班卡
                    //进行下班打卡
                    boolean blIsCheck = attendanceService.isCheckAttendance(user, groupUser,1);//判断上午是否打卡
                    if (blIsCheck) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未到下午上班打卡时间，可提前"+ pmBeginDutyHour +"小时打卡"),true,true);
                    }
                    Attendance attendance = packageAttendance(user_id, groupUser, lng, lat, address, remark, amEndDutyTime, isOut, 1, null, imgUrl, attendanceGroup.getId());
                    ret = attendanceService.addCheck(attendance);
                }
                //下午上班卡 12：30 ~ 13：30
                else if (pmBeginDutyTimeBefore.getTime() <= nowDate.getTime() && nowDate.getTime() <= pmBeginDutyTime.getTime()) {//打上班卡
                    //进行上班打卡
                    boolean blIsCheck = attendanceService.isCheckAttendance(user, groupUser,2);//判断上午是否打卡
                    if (blIsCheck) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"已打卡，无需打卡"),true,true);
                    }
                    //半小时内算迟到
                    Date halfHourAfter = DateUtil.getDateByMinuts(pmBeginDutyTime, 30);
                    Attendance attendance = packageAttendance(user_id, groupUser, lng, lat, address, remark, pmBeginDutyTime, isOut, 2, halfHourAfter, imgUrl, attendanceGroup.getId());
                    ret = attendanceService.addCheck(attendance);
                }
                // 下午上班之后  这段期间 迟到卡  13：30 ~ 17：20
                else if (pmBeginDutyTime.getTime() <= nowDate.getTime() && nowDate.getTime() < pmEndDutyTime.getTime()) {
                    boolean blIsCheck = attendanceService.isCheckAttendance(user,groupUser, 2);//判断下午是否打卡
                    if (blIsCheck) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未到下班时间"),true,true);
                    }
                    //半小时内算迟到
                    Date halfHourAfter = DateUtil.getDateByMinuts(pmBeginDutyTime, 30);
                    Attendance attendance = packageAttendance(user_id, groupUser, lng, lat, address, remark, pmBeginDutyTime, isOut, 2, halfHourAfter, imgUrl, attendanceGroup.getId());
                    ret = attendanceService.addCheck(attendance);
                }
                // 下午下班卡   17：20 ~ 23：59：59
                else if (pmEndDutyTime.getTime() <= nowDate.getTime() && nowDate.getTime() <= lastTime.getTime()) {//打下班卡
                    boolean blIsCheck = attendanceService.isCheckAttendance(user,groupUser, 3);//判断下午是否打卡
                    if (blIsCheck) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未达下班打卡时间，请下班后打卡"),true,true);
                    }
                    Attendance attendance = packageAttendance(user_id, groupUser, lng, lat, address, remark,
                            pmEndDutyTime, isOut, 3, null, imgUrl, attendanceGroup.getId());
                    ret = attendanceService.addCheck(attendance);
                }

                if (ret > 0) {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"打卡成功", ret),true,false);
                } else {
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"打卡失败,当前打卡时间是否合理"),true,true);
                }
            } else {
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未匹配考勤组"),true,true);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"打卡失败"),true,true);
        }
        return result;
    }

    /**
     *  审核人员查看的 请假记录
     * @param requestParam
     * @return
     */
    @PostMapping(value = "/holiday/record/list")
    public JSONObject holidayRecordList(@RequestBody String requestParam) {
        JSONObject result = null;
        try {
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "attendance/holiday/record/list 接收的参数： " + requestParam);
            logger.info("考勤详情 attendance/holiday/record/list 接收参数：" + requestParam);
            System.out.println("attendance/holiday/record/list 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 20;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            AttendanceGroupUser groupUser = attendanceGroupUserService.getCheckHolidayManager(0, user);
            if(groupUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无审核权限"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            QueryWrapper<Attendance> qw = new QueryWrapper<>();
            if(groupUser.getUserType() == 0){
                qw.eq("property_id",groupUser.getPropertyId());
            }else{
                qw.eq("estate_id",groupUser.getEstateId());
            }
            qw.eq("state",4);//请假状态的
            //请假状态  0 - 非请假状态  1 - 未处理  2 - 未批准 3 -  已批准
            if(state > -1){
                qw.eq("holiday_state",state);//请假处理状态
            }
            qw.orderByDesc("create_time");
            List<Attendance> list = attendanceService.getPageEntityList(qw, pageIndex, pageSize);
            for (Attendance attendance : list){

                if(StrUtil.isNotEmpty(attendance.getLeaveType())){
                    SysDictData sysDictData = sysDictDataService.selectDictData("holiday_leave_type",attendance.getLeaveType());
                    if(sysDictData!=null){
                        attendance.setLeaveTypeStr(sysDictData.getDictLabel());
                    }
                }
                attendance.setLeaveBeginDateStr(DateUtil.getTimesStr(attendance.getLeaveBeginDate()));
                attendance.setLeaveEndDateStr(DateUtil.getTimesStr(attendance.getLeaveEndDate()));
                User user1 = userService.findById(attendance.getUserId());
                if(user1 != null){
                    attendance.setFaceUrl(user1.getFaceUrl());
                    if(StrUtil.isNotEmpty(user1.getNickName())){
                        attendance.setNickName(EmojiParser.parseToUnicode(user1.getNickName()));
                    }
                }
            }
            map.put("records",list);

            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功",list.size(),map),false,false);
        } catch (Exception e) {
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常"),true,true);
            logger.error("考勤详情异常报错", e);
        }
        return result;
    }


    /**
     *  个人的 打卡记录
     * @param requestParam
     * @return
     */
    @PostMapping(value = "/record/list")
    public JSONObject recordList(@RequestBody String requestParam) {
        JSONObject result = null;
        try {
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "attendance/record/list 接收的参数： " + requestParam);
            logger.info("考勤详情 attendance/record/list 接收参数：" + requestParam);
            System.out.println("attendance/record/list 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int state = jsonRequest.containsKey("state") ? jsonRequest.getInt("state") : 1;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 20;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            Map<String,Object> map = new HashMap<>();
            QueryWrapper<Attendance> qw = new QueryWrapper<>();
            if(state == 1){
                Integer[] states = {1,2,3};
                qw.in("state", Arrays.asList(states));
            } else{
                qw.eq("state", state);
            }
            qw.eq("user_id",user_id);
            qw.orderByDesc("create_time");
            List<Attendance> list = attendanceService.getPageEntityList(qw,pageIndex,pageSize);
            for (Attendance attendance : list){

                if(attendance.getLeaveBeginDate()!=null){
                    attendance.setLeaveBeginDateStr(DateUtil.getTimesStr(attendance.getLeaveBeginDate()));
                }
                if(attendance.getLeaveEndDate()!=null){
                    attendance.setLeaveEndDateStr(DateUtil.getTimesStr(attendance.getLeaveEndDate()));
                }

                if(StrUtil.isNotEmpty(attendance.getLeaveType())){
                    SysDictData sysDictData = sysDictDataService.selectDictData("holiday_leave_type",attendance.getLeaveType());
                    if(sysDictData!=null){
                        attendance.setLeaveTypeStr(sysDictData.getDictLabel());
                    }
                }

                User user1 = userService.findById(attendance.getUserId());
                if(user1 != null){
                    if(StrUtil.isNotEmpty(user1.getFaceUrl())){
                        if(user1.getFaceUrl().contains("https")){
                            attendance.setFaceUrl(user1.getFaceUrl());
                        }else{
                            attendance.setFaceUrl(imgPrefix + user.getFaceUrl());
                        }
                    }
                    if(StrUtil.isNotEmpty(user1.getNickName())){
                        attendance.setNickName(EmojiParser.parseToUnicode(user1.getNickName()));
                    }
                }


                List<String> imgUrls = new ArrayList<>();
                QueryWrapper<AttendanceImg> qwImg = new QueryWrapper<>();
                qwImg.eq("attendance_id", attendance.getId());
                List<AttendanceImg> imgs = attendanceImgService.list(qwImg);
                if(CollUtil.isNotEmpty(imgs)){
                    for (AttendanceImg img : imgs){
                        imgUrls.add(imgPrefix + img.getImgUrl());
                    }
                }
                attendance.setImgUrlList(imgUrls);
            }
            map.put("records",list);

            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功",list.size(), map),false,false);
        } catch (Exception e) {
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常"),true,true);
            logger.error("考勤详情异常报错", e);
        }
        return result;
    }


    /**
     * 考勤  请假操作
     * @param requestParam
     * @return
     */
    @PostMapping(value = "/leave/view")
    public Object leaveView(@RequestBody String requestParam) {
        Object result = null;
        try {
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "attendance/leave/view 接收的参数： " + requestParam);
            logger.info("考勤详情 attendance/leave/view 接收参数：" + requestParam);
            System.out.println("attendance/leave/view 接收的参数： " + requestParam + "      " +  DateUtil.getTime());
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);

            Map<String,Object> map = new HashMap<>();
            List<String> typeNames = new ArrayList<>();
            List<SysDictData> leaveTypes = sysDictDataService.selectDictDataList("holiday_leave_type");
            if(CollUtil.isNotEmpty(leaveTypes)){
                for (SysDictData dictData : leaveTypes){
                    typeNames.add(dictData.getDictLabel());
                }
            }
            map.put("leaveTypeNames",typeNames);
            map.put("leaveTypes",leaveTypes);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"请假申请成功",map),true,false);
        } catch (Exception e) {
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请假申请异常"),true,true);
            logger.error("考勤打卡异常", e);
        }
        return result;
    }

    /**
     * 考勤  请假操作
     * @param jsonRequest
     * @return
     */
    @PostMapping(value = "/leave")
    public Object attendanceLeave(@RequestBody JSONObject jsonRequest) {
        Object result = null;
        try {
            logger.info("考勤请假 attendance/leave 接收参数： " + jsonRequest.toString());
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String leaveBeginDate = jsonRequest.containsKey("leaveBeginDate") ? jsonRequest.getStr("leaveBeginDate") : null;
            String leaveBeginTime = jsonRequest.containsKey("leaveBeginTime") ? jsonRequest.getStr("leaveBeginTime") : null;
            String leaveEndDate = jsonRequest.containsKey("leaveEndDate") ? jsonRequest.getStr("leaveEndDate") : null;
            String leaveEndTime = jsonRequest.containsKey("leaveEndTime") ? jsonRequest.getStr("leaveEndTime") : null;
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : null;
            String leaveType = jsonRequest.containsKey("leaveType") ? jsonRequest.getStr("leaveType") : null;
            double leaveTime = jsonRequest.containsKey("leaveTime") ? jsonRequest.getDouble("leaveTime") : 0;
            String imgs = jsonRequest.containsKey("imgs") ? jsonRequest.getStr("imgs") : null;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            AttendanceGroupUser groupUser = attendanceGroupUserService.getDefaultGroup(user);
            if(groupUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定OA办公人员"),true,true);
            }

            SysUser sysUser = sysUserService.findById(groupUser.getSysUserId());
            if(sysUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"未绑定考勤人员，无需打卡"),true,true);
            }

            int ret = attendanceService.addLeave(user,sysUser,leaveType,leaveBeginDate,leaveBeginTime,leaveEndDate,leaveEndTime,remark,leaveTime,imgs);//判断下午是否打卡
            if (ret > 0) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"请假申请成功"),true,true);
            } else if (ret == -99) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前时间不能重复请假"),true,true);
            } else {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请假申请失败"),true,true);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请假申请异常"),true,true);
            logger.error("考勤打卡异常", e);
        }
        return result;
    }



    /**
     * 图片上传
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    public JSONObject uploadImgRepair(@RequestParam("record_id") int record_id, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            Attendance attendance = attendanceService.getById(record_id);
            if(attendance == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "该记录不存在"), true, true);
            }
            boolean bl = false;
            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certUrl = maps.get(key);
                        if (!certUrl.isEmpty()) {
                            String prefix = certUrl.getOriginalFilename().substring(certUrl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "examine_approve_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certUrl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_ATTENDANCE;

                                        String img_key = OssUtil.getUploadPrefix(upload_type) + DateUtil.getSdfYearDay() + "/" + fileName;

                                        String path = uploadPath + OssUtil.getUploadPrefix(upload_type) + DateUtil.getSdfYearDay() ;
                                        System.out.println("path: " + path);
                                        File file = new File(path);
                                        if (!file.exists() && !file.isDirectory()) {
                                            file.mkdirs();
                                        }

                                        String filePath =  path +"/" + fileName;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certUrl.getBytes());
                                        out.flush();
                                        out.close();

                                        ImagesFiler.imageResize(filePath,filePath);

                                        AttendanceImg img = new AttendanceImg();
                                        img.setAttendanceId(record_id);
                                        img.setImgType(0);
                                        img.setImgUrl(img_key);
                                        img.setCreatTime(new Date());
                                        bl = attendanceImgService.save(img);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    return Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                }
                            }
                        }
                    }
                }
            }

            if(bl){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "图片上传失败"), true, true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

    /**
     *  生成打卡记录
     * @param userId
     * @param groupUser
     * @param lng
     * @param lat
     * @param address
     * @param remark
     * @param dutyTime
     * @param isOut
     * @param type
     * @param afterHalf
     * @param imgUrl
     * @param groupId
     * @return
     */
    private Attendance packageAttendance(int userId, AttendanceGroupUser groupUser, Double lng, Double lat, String address, String remark, Date dutyTime,
                                         Integer isOut, Integer type, Date afterHalf, String imgUrl, Integer groupId) {

        Attendance attendance = new Attendance();
        attendance.setPropertyId(groupUser.getPropertyId());
        attendance.setEstateId(groupUser.getEstateId());
        attendance.setDutyGroupId(groupId);
        if(groupUser.getEstateId() != null && groupUser.getEstateId() > 0){
            Estate estate = estateService.findById(groupUser.getEstateId());
            if(estate!=null){
                attendance.setEstateName(estate.getEstateName());
            }
        }
        attendance.setUserId(userId);
        attendance.setCreateTime(new Date());
        attendance.setSysUserId(groupUser.getSysUserId());

        SysUser sysUser = sysUserService.findById(groupUser.getSysUserId());
        if(sysUser != null){
            attendance.setSysUserName(sysUser.getNickName());
            attendance.setDeptId(sysUser.getDeptId());
        }
        attendance.setState(1);
        // state  打卡状态  1 - 正常  2-  迟到  3- 旷工  4 - 请假
//        if (type == 0) {//上午打卡
//        } else {//下午打卡
//
//        }
        if(type < 3){//下午下班打开
            //打卡状态  1 - 正常  2-  迟到  3- 旷工  4 - 请假   5 - 早退
            //打卡时间 晚于 dutyTime    迟到 （迟到半小时 属于迟到）
            if(afterHalf!= null){
                if (new Date().getTime() > dutyTime.getTime() && dutyTime.getTime() < afterHalf.getTime()) {
                    attendance.setState(2);
                } else if (new Date().getTime() > afterHalf.getTime()) {
                    attendance.setState(3);
                }
            }
        }
        attendance.setHolidayState(0);
        attendance.setImgs(imgUrl);
        attendance.setAmOrPm(type);
        attendance.setDutyTime(dutyTime);
        attendance.setLng(lng);
        attendance.setLat(lat);
        attendance.setAddress(address);
        attendance.setRemark(remark);
        //是否是外勤打卡 0 -正常  1-  外勤打卡 2 -  请假
        attendance.setIsOut(isOut);
        attendance.setTotalSignCount(1);
        attendance.setDutyGroupId(groupId);
        return attendance;
    }

    private int isNeedDaka(int weekDay, AttendanceGroup attendanceGroup) {
        int ret = 1;
        if (weekDay == 1 && attendanceGroup.getWorkDay1() == 0) {
            ret = 0;
        } else if (weekDay == 2 && attendanceGroup.getWorkDay2() == 0) {
            ret = 0;
        } else if (weekDay == 3 && attendanceGroup.getWorkDay3() == 0) {
            ret = 0;
        } else if (weekDay == 4 && attendanceGroup.getWorkDay4() == 0) {
            ret = 0;
        } else if (weekDay == 5 && attendanceGroup.getWorkDay5() == 0) {
            ret = 0;
        } else if (weekDay == 6 && attendanceGroup.getWorkDay6() == 0) {
            ret = 0;
        } else if (weekDay == 7 && attendanceGroup.getWorkDay7() == 0) {
            ret = 0;
        }

        //休息时间
        QueryWrapper<AttendanceOffWork> qw = new QueryWrapper<>();
        qw.eq("group_id", attendanceGroup.getId());
        qw.le("start_time",new Date());
        qw.ge("end_time",new Date());
//        qw.ge("on_or_off", 0);
        qw.ge("is_default", 0);
        qw.last("limit 1");
        //当前考勤组有自己的  作息调休时间
        AttendanceOffWork offWork = attendanceOffWorkService.getOne(qw);
        if (offWork != null) {
            //调休时间
            if(offWork.getOnOrOff() == 0){
                ret = 0;
            }else{
                ret = 1;
            }
        }else{
            qw.clear();
            qw = new QueryWrapper<>();
            qw.le("start_time",new Date());
            qw.ge("end_time",new Date());
//            qw.ge("on_or_off", 0);
            qw.ge("is_default", 1);
            qw.last("limit 1");
            offWork = attendanceOffWorkService.getOne(qw);
            if(offWork != null){
                //调休时间
                if(offWork.getOnOrOff() == 0){
                    ret = 0;
                }else{
                    ret = 1;
                }
            }
        }
        return ret;
    }
}
